﻿Imports System.ComponentModel
Imports System.Windows.Media.Animation
Imports System.Runtime.InteropServices
Imports System.Windows.Interop
Imports System.Net


Class MainWindow
    Implements INotifyPropertyChanged

    Protected WithEvents monitor As EQATEC.Analytics.Monitor.IAnalyticsMonitor
    Protected WithEvents FileOpener As BackgroundWorker
    Protected WithEvents saveFileBGW As BackgroundWorker

    Private _comic As Comic
    Private _rl As ReadingList
    Private start As Point
    Private origin As Point
    Private _mru As New MostRecentFiles
    Private _isFullScreen As Boolean = False
    Private _resumeReadingVal As Integer = 0
    Private _bright As Double = 0
    Private _contrast As Double = 0
    Private _isLandscape As Boolean = True

    Private _currentVersionUrl As String = String.Empty
    Private _displayUpdate As Boolean = False

    Private _useLocalMonitor As Boolean = True
#Region "Properties"
    Public ReadOnly Property MRU As MostRecentFiles
        Get
            Return _mru
        End Get
    End Property
    Public ReadOnly Property Pages As ComicPages
        Get
            If _comic Is Nothing Then
                Return New ComicPages()
            Else
                Return _comic.ComicPages
            End If
        End Get
    End Property
    Public ReadOnly Property CurrentPage() As String
        Get
            Return (Me.lstPages.SelectedIndex + 1).ToString
        End Get
    End Property
    Public ReadOnly Property CurrentFileName() As String
        Get
            Dim s As String = ""
            If Not Me.lstPages.SelectedItem Is Nothing Then
                s &= CType(Me.lstPages.SelectedItem, comicPage).FileName
            End If
            Return s
        End Get
    End Property
    Public ReadOnly Property PageCount As Integer
        Get
            If _comic Is Nothing Then
                Return 0
            Else
                Return _comic.ComicPages.Count
            End If
        End Get
    End Property
    Public Property SelectedPage As Integer
        Get
            If Not lstPageNames.SelectedItem Is Nothing Then
                Return Me.lstPages.SelectedIndex
            Else
                Return 0
            End If
        End Get
        Set(ByVal value As Integer)
            Me.lstPages.SelectedIndex = value
        End Set
    End Property
    Public Property Comic As Comic
        Get
            Return _comic
        End Get
        Set(ByVal value As Comic)
            _comic = value
        End Set
    End Property

    Public Property DisplayUpdate As Boolean
        Get
            Return _displayUpdate
        End Get
        Set(ByVal value As Boolean)
            _displayUpdate = value
            OnPropertyChanged("DisplayUpdate")
        End Set
    End Property

    Public Property Brightness As Double
        Get
            Return _bright
        End Get
        Set(ByVal value As Double)
            If value > 1 Then value = 1
            If value < -1 Then value = -1
            _bright = value
            OnPropertyChanged("Brightness")
        End Set
    End Property
    Public Property Contrast As Double
        Get
            Return _contrast
        End Get
        Set(ByVal value As Double)
            If value > 1 Then value = 1
            If value < -1 Then value = -1
            _contrast = value
            OnPropertyChanged("Contrast")
        End Set
    End Property

    Public ReadOnly Property IsFavorite As Boolean
        Get
            Dim x As Boolean = False
            If Not _comic Is Nothing Then
                x = _comic.IsFavorite
            End If
            Return x
        End Get
    End Property
    Public ReadOnly Property IsNotFavorite As Boolean
        Get
            Dim x As Boolean = True
            If Not _comic Is Nothing Then
                x = Not _comic.IsFavorite
            End If
            Return x
        End Get
    End Property

#End Region


#Region "Helper Methods"
    Protected Sub RunOpenCommand()
        monitor.TrackFeature("OpenFile.Standard")
        Me.Cursor = Cursors.Wait
        Dim f As New Windows.Forms.OpenFileDialog
        f.Multiselect = False
        f.Filter = "All Files (*.*)|*.*|Comic Book Archives (*.cbr, *.cbz, *.cb7, *.rar, *.zip)|*.cbr;*.cbz;*.cb7;*.rar;*.zip|Graphic Novel Archives (*.gnr, *.gnz)|*.gnr;*.gnz|Comic Book PDF (*.pdf)|*.pdf"
        f.FilterIndex = 1
        Dim dlg As Windows.Forms.DialogResult = f.ShowDialog
        If dlg = Forms.DialogResult.OK Then
            If FileOpener.IsBusy Then FileOpener.CancelAsync()
            If Not _comic Is Nothing Then _comic.Dispose()
            If Not _rl Is Nothing Then _rl.Dispose()
            My.Settings.LastFileStoppedPage = 0
            FileOpener.RunWorkerAsync(f.FileName)
        Else
            Me.Cursor = Cursors.Arrow
        End If ' dlg = Forms.DialogResult.OK 
    End Sub

    Protected Sub RunOpenDirCommand()
        Me.Cursor = Cursors.Wait
        Dim f As New Windows.Forms.FolderBrowserDialog
        f.Description = "Select the folder to be opened inside of eComic"
        Dim dlg As Windows.Forms.DialogResult = f.ShowDialog
        If dlg = Forms.DialogResult.OK Then
            If FileOpener.IsBusy Then FileOpener.CancelAsync()
            If Not _comic Is Nothing Then _comic.Dispose() : _comic = Nothing
            If Not _rl Is Nothing Then _rl.Dispose() : _rl = Nothing
            My.Settings.LastFileStoppedPage = 0
            FileOpener.RunWorkerAsync(f.SelectedPath)
        Else
            Me.Cursor = Cursors.Arrow
        End If
    End Sub

    Public Sub LoadFileFromCommandLine(ByVal fileName As String)
        monitor.TrackFeature("OpenFile.CommandLine")
        If IO.File.Exists(fileName) Then FileOpener.RunWorkerAsync(fileName)
    End Sub ' LoadFileFromCommandLine 

    Protected Sub performZoom(ByVal zoom As Double)
        If Not Me._comic Is Nothing AndAlso Not Me.lstPages Is Nothing AndAlso Not Me.lstPages.SelectedItem Is Nothing AndAlso Me.lstPages.SelectedItem.GetType Is GetType(comicPage) Then
            Dim transformGroup As TransformGroup = DirectCast(Me.imgFull.RenderTransform, TransformGroup)
            Dim transform As ScaleTransform = DirectCast(transformGroup.Children(0), ScaleTransform)
            transform.ScaleX += zoom
            transform.ScaleY += zoom
            Me.imgFull.InvalidateVisual()
        End If
    End Sub

    Protected Sub navigateList(ByVal goForward As Boolean)
        Dim i As Integer = Me.lstPages.SelectedIndex
        If goForward Then
            If i < Me.Pages.Count - 1 Then i += 1
        Else ' goForward = True 
            If i > 0 Then i -= 1
        End If ' goForward = True 
        Me.lstPages.SelectedIndex = i
        Me.lstPages.ScrollIntoView(Me.lstPages.SelectedItem)
    End Sub

    Protected Sub reverseZoom(ByVal stretch As Stretch)

        Dim group As New TransformGroup
        Dim xForm As New ScaleTransform
        group.Children.Add(xForm)

        Dim tt As New TranslateTransform
        group.Children.Add(tt)

        Me.imgFull.RenderTransform = group
        Me.imgFull.Stretch = stretch
        Me.imgFull.InvalidateVisual()
    End Sub

    ''' <summary>
    ''' Shows/Hides the "Full Screen Control Panel" pop-up element 
    ''' </summary>
    ''' <param name="show">Determines if the Full Screen Control Panel is oepn </param>
    ''' <remarks></remarks>
    Protected Sub DisplayPop(ByVal show As Boolean)
        Me.popFullScreenControlPanel.HorizontalOffset = (Me.imgBorder.ActualWidth / 2) - (Me.spFullScreenControlPanel.ActualWidth / 2)
        Me.spFullScreenControlPanel.Visibility = Windows.Visibility.Visible
        Me.popFullScreenControlPanel.IsOpen = show
    End Sub

    Protected Sub goFullScreen()
        If My.Settings.ReportMetrics Then monitor.TrackFeature("FullScreen")
        If My.Settings.ReportMetrics Then monitor.TrackFeatureStart("FullScreen")
        Me.WindowStyle = WindowStyle.None
        ' Me.Topmost = True
        Me.ribbonMenu.Visibility = Windows.Visibility.Collapsed
        Me.lstPages.Visibility = Visibility.Collapsed
        Me.statusBar1.Visibility = Windows.Visibility.Collapsed
        Me.brdListPages.Visibility = Windows.Visibility.Collapsed
        Me.WindowState = Windows.WindowState.Maximized

        DisplayPop(True)
        _isFullScreen = True
    End Sub

    Protected Sub exitFullScreen()
        If My.Settings.ReportMetrics Then monitor.TrackFeatureStop("FullScreen")
        Me.Topmost = False
        Me.WindowStyle = WindowStyle.SingleBorderWindow
        Me.ribbonMenu.Visibility = Windows.Visibility.Visible
        Me.lstPages.Visibility = Visibility.Visible
        Me.statusBar1.Visibility = Windows.Visibility.Visible
        Me.brdListPages.Visibility = Visibility.Visible
        Me.WindowState = Windows.WindowState.Normal
        Me.spFullScreenControlPanel.Visibility = Windows.Visibility.Collapsed
        Me.popFullScreenControlPanel.IsOpen = False
        _isFullScreen = False
    End Sub

    Protected Sub runGoToPage()
        Dim dlg As New gotoPage
        dlg.Maximum = Me._comic.ComicPages.Count
        dlg.SelectedPage = Me.lstPages.SelectedIndex
        If dlg.ShowDialog Then Me.lstPages.SelectedIndex = dlg.SelectedPage
    End Sub

    ''' <summary>
    ''' The PAN animation 
    ''' </summary>
    ''' <param name="toValue"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CreatePanAnimation(ByVal toValue As Double) As DoubleAnimation
        Dim da = New DoubleAnimation(toValue, New Duration(TimeSpan.FromMilliseconds(300)))
        da.AccelerationRatio = 0.1
        da.DecelerationRatio = 0.9
        da.FillBehavior = FillBehavior.HoldEnd
        da.Freeze()
        Return da
    End Function

    ''' <summary>
    ''' Handles changes to items based on binding 
    ''' </summary>
    ''' <remarks></remarks>
    Protected Sub ElementRefreshes()
        Me.OnPropertyChanged("Comic")
        Me.OnPropertyChanged("Pages")
        Me.OnPropertyChanged("CurrentPage")
        Me.OnPropertyChanged("SelectedPage")
        Me.OnPropertyChanged("CurrentFileName")
        Me.OnPropertyChanged("IsFavorite")
        Me.OnPropertyChanged("IsNotFavorite")
    End Sub

    ''' <summary>
    ''' Loads a the next archive in the list
    ''' </summary>
    ''' <param name="goForward">Determines if the archive loaded is the next or the previous element in the list</param>
    ''' <remarks></remarks>
    Protected Sub goToOtherArchive(ByVal goForward As Boolean)
        monitor.TrackFeature(IIf(goForward, "OpenFile.GoNextArchive", "OpenFile.GoPreviousArchive"))
         If FileOpener.IsBusy Then FileOpener.CancelAsync()
        Dim fn As String
        If goForward Then
            If _rl.HasNext Then
                fn = _rl.GetNextFile
            Else ' _rl.HasNext 
                fn = _rl.getFileByIndex(0)
            End If ' _rl.HasNext 
        Else ' goForward 
            If _rl.HasPrevious Then
                fn = _rl.GetPreviousFile
            Else ' _rl.HasPrevious 
                fn = _rl.getFileByIndex(_rl.FileList.Count - 1)
            End If ' _rl.HasPrevious 
        End If ' goForward 

        If IO.File.Exists(fn) Then
            If Not _comic Is Nothing Then _comic.Dispose()
            Me.Cursor = Cursors.Wait
            Me.FileOpener.RunWorkerAsync(fn) ' TODO :  Consider toggle for delete/create of the Reading list 
        Else ' IO.File.Exists(fn) 
            MsgBox("Error finding next archive.", MsgBoxStyle.Information, "eComic")
            Me.Cursor = Cursors.Arrow
        End If ' IO.File.Exists(fn) 
    End Sub

    ''' <summary>
    ''' Switches the screen to use LANDSCAPE mode functionality 
    ''' </summary>
    ''' <remarks></remarks>
    Protected Sub goToLandscapeMode()
        Me.brdListPagesBottom.Visibility = Windows.Visibility.Collapsed
        Me.brdListPages.Visibility = Windows.Visibility.Visible
        _isLandscape = True
    End Sub

    ''' <summary>
    ''' Switches the screen to use the PORTRAIT MODE functionality 
    ''' </summary>
    ''' <remarks></remarks>
    Protected Sub goToPortriatMode()
        Me.brdListPages.Visibility = Windows.Visibility.Collapsed
        Me.brdListPagesBottom.Visibility = Windows.Visibility.Visible
        _isLandscape = False
    End Sub
#End Region


#Region "Event Items"
    Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
    Public Overloads Sub OnPropertyChanged(ByVal propertyName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

#End Region

#Region "eComic Main Form Event Handlers"
    Private Sub eComic_Initialized(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Resources.MergedDictionaries.Add(Microsoft.Windows.Controls.Ribbon.PopularApplicationSkins.Office2007Silver)
        Me.DataContext = Me

        FileOpener = New BackgroundWorker
        FileOpener.WorkerReportsProgress = True
        FileOpener.WorkerSupportsCancellation = True
        saveFileBGW = New BackgroundWorker
        saveFileBGW.WorkerReportsProgress = True
        saveFileBGW.WorkerSupportsCancellation = False

        ' Monitoring Software 
        If _useLocalMonitor Then
            Dim xyz As New EQATEC.Analytics.Monitor.AnalyticsMonitorSettings("387A996B54D94D0BA180EDA1019F0753")
            xyz.ServerUri = New Uri("http://localhost:56374/")
            xyz.Version = New Version(2010, 0, 0, 2)
            monitor = EQATEC.Analytics.Monitor.AnalyticsMonitorFactory.Create(xyz) ' "387A996B54D94D0BA180EDA1019F0753")
        Else
            monitor = EQATEC.Analytics.Monitor.AnalyticsMonitorFactory.Create("387A996B54D94D0BA180EDA1019F0753")
        End If
        If My.Settings.ReportMetrics Then monitor.Start()
        AddHandler monitor.VersionAvailable, AddressOf monitor_versionAvailable


        monitor.SendLog("Test Message")
        monitor.TrackException(New System.Exception("Test Exception"))

        ' Support for switching screen orientation 
        AddHandler Microsoft.Win32.SystemEvents.DisplaySettingsChanged, AddressOf DetectScreenRotation
        Dim theScreenHeight As Integer
        Dim theScreenWidth As Integer ' TODO: Find way to determine currently used screen 
        theScreenHeight = Forms.Screen.PrimaryScreen.Bounds.Height
        theScreenWidth = Forms.Screen.PrimaryScreen.Bounds.Width
        If (theScreenHeight > theScreenWidth) Then
            Debug.WriteLine("Run the application in portrait")
            Me.goToPortriatMode()
        Else ' (theScreenHeight > theScreenWidth) 
            Debug.WriteLine("Run the application in landscape")
            Me.goToLandscapeMode()
        End If ' (theScreenHeight > theScreenWidth) 


        ' Build the MRU List 
        Dim file_name As String
        For i As Integer = 1 To My.Settings.MRUCount
            file_name = GetSetting("eComic", "MruList", "FileName" & i, "")
            If file_name.Length > 0 AndAlso IO.File.Exists(file_name) Then
                MRU.Append(New MostRecentFile(file_name, True))
            End If ' file_name.Length > 0 
        Next
        Me.mruList.ItemsSource = _mru
        Me.mruList.Items.Refresh()


        ' These items are used for the  PAN/ZOOM functions 
        Dim group As New TransformGroup
        Dim xForm As New ScaleTransform
        group.Children.Add(xForm)
        Dim tt As New TranslateTransform
        group.Children.Add(tt)
        Me.imgFull.RenderTransform = group


        ' This is used for the loupe magnification 
        Dim b As VisualBrush = DirectCast(magnifierEllipse.Fill, VisualBrush)
        b.Visual = Me.imgBorder

    End Sub

    Private Sub eComic_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.DragEventArgs)
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effects = DragDropEffects.Copy
        Else ' e.Data.GetDataPresent(DataFormats.FileDrop) 
            e.Effects = DragDropEffects.None
        End If ' e.Data.GetDataPresent(DataFormats.FileDrop) 
    End Sub ' eComic_DragEnter 

    Private Sub eComic_Drop(ByVal sender As System.Object, ByVal e As System.Windows.DragEventArgs)
        Try
            monitor.TrackFeature("OpenFile.DragDrop")
            Dim a As Array = CType(e.Data.GetData(DataFormats.FileDrop), Array)
            If Not a Is Nothing Then
                ' Get the string from the first array element (ignoring all files except first if multiple files are dropped)
                Dim fileName As String = a.GetValue(0).ToString
                ' Then we call the Open File as asynchronous format
                '   Explorer instance from which file is dropped is not responding all the time 
                '   when drapDrop handlers are active. Need to return immediate so that the 
                '   Explorer can continue its own processing.
                If IO.File.Exists(fileName) Then FileOpener.RunWorkerAsync(fileName)
                Me.Activate()
            End If
        Catch ex As Exception
            Debug.WriteLine("Error in drapDrop: " & ex.Message)
        End Try
    End Sub ' eComic_Drop 

    Private Sub eComic_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs)
        My.Settings.Save()

        ' Clean up the COMIC
        If Not _comic Is Nothing Then _comic.Dispose() : _comic = Nothing

        ' Clean up the Existing MRU LIST and rebuild from scratch 
        If GetSetting("eComic", "MruList", "FileName1", "").Length > 0 Then DeleteSetting("eComic", "MruList")

        Dim i As Integer = 0
        Do While i < MRU.Count
            SaveSetting("eComic", "MruList", "FileName" & i + 1, MRU(i).FilePath.ToString)
            SaveSetting("ecomic", "MruList", "CurrentPage" & i + 1, MRU(i).PageNumber.ToString)
            i += 1
        Loop
    End Sub

    Private Sub eComic_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs)
        Select Case e.Key
            Case Key.Add
                Me.performZoom(0.2)
                e.Handled = True
            Case Key.Subtract
                Me.performZoom(-0.2)
                e.Handled = True
            Case Key.Down, Key.PageDown
                Me.navigateList(True)
                e.Handled = True
            Case Key.Up, Key.PageUp
                Me.navigateList(False)
                e.Handled = True
            Case Key.Escape
                exitFullScreen()
                e.Handled = True
            Case Key.F12
                DisplayPop(Not Me.popFullScreenControlPanel.IsOpen)
                e.Handled = True
            Case Key.F11
                If _isFullScreen Then
                    Me.exitFullScreen()
                Else ' _isFullScreen = True 
                    Me.goFullScreen()
                End If ' _isFullScreen = True 
                e.Handled = True
            Case Key.F8
                If _isLandscape Then
                    Me.goToPortriatMode()
                Else
                    Me.goToLandscapeMode()
                End If
        End Select
        If e.KeyboardDevice.Modifiers = ModifierKeys.Control Then
            Select Case e.Key
                Case Key.O
                    RunOpenCommand()
                    e.Handled = True
                Case Key.L
                    Me.chkLoupe.IsChecked = Not Me.chkLoupe.IsChecked
                    e.Handled = True
            End Select
        End If
    End Sub

    Private Sub eComic_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Me.MouseDoubleClick
        If Not _isFullScreen Then
            Me.goFullScreen()
        End If ' Not Me._isFullScreen 
    End Sub ' eComic_MouseDoubleClick 

    Private Sub eComic_MouseWheel(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseWheelEventArgs)
        If Not CBool(My.Settings.MouseWheelZoom) Then navigateList(Not (e.Delta > 0))
    End Sub ' eComic_MouseWheel 

#End Region

#Region "File Opener Background Worker"
    Private Sub FileOpener_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles FileOpener.DoWork
        Try
            Dim fileName As String = e.Argument.ToString
            Dim comic As Comic
            Dim rl As ReadingList

            Dim ext As String = IO.Path.GetExtension(fileName)
            If ext.Contains("gn") Then
                ' TODO : Implement Reading List 
                e.Cancel = True
                Exit Sub
                'bw.rl = New readingList(bw.fileName)
                'If FileOpener.CancellationPending Then e.Cancel = True : Exit Sub
                'bw.comic = New Comic(_rl.getFileByIndex(0))
                'If FileOpener.CancellationPending Then e.Cancel = True : Exit Sub
            Else ' ext.Contains("gn") 
                comic = New Comic(fileName)
                If FileOpener.CancellationPending Then e.Cancel = True : e.Result = String.Empty : Exit Sub

                rl = New ReadingList(fileName)
                If FileOpener.CancellationPending Then e.Cancel = True : e.Result = String.Empty : Exit Sub

            End If ' ext.Contains("gn") 

            FileOpener.ReportProgress(1, rl)
            FileOpener.ReportProgress(2, comic)

            Dim fileList As New List(Of String)
            Select Case comic.ArchiveType
                Case ArchiveType.CBR
                    If Not IO.Directory.Exists(comic.TempFolder) Then IO.Directory.CreateDirectory(comic.TempFolder)
                    Dim d As New unRar.Decompressor(comic.Path)
                    Dim b As Boolean = True
                    Dim x As Integer = d.RARFiles.Count
                    FileOpener.ReportProgress(5, x)
                    For Each rarentry In d.RARFiles
                        b = d.UnPack(rarentry.Filename, comic.TempFolder)
                        If FileChecker.CheckImageFileName(rarentry.FileName) Then fileList.Add(comic.TempFolder & "\" & rarentry.filename)
                        If Not b Then
                            e.Cancel = True
                            e.Result = "CBR File Failed to Decompress."
                            Exit Sub
                        End If ' Not b = True 
                        If FileOpener.CancellationPending Then e.Cancel = True : e.Result = String.Empty : Exit Sub
                        FileOpener.ReportProgress(6, x)


                    Next

                Case ArchiveType.CBZ

                    Using zip1 As Ionic.Zip.ZipFile = Ionic.Zip.ZipFile.Read(comic.Path)
                        Dim zipItem As Ionic.Zip.ZipEntry
                        Dim x As Integer = zip1.Count
                        FileOpener.ReportProgress(5, x)
                        For Each zipItem In zip1
                            zipItem.Extract(comic.TempFolder, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
                            If FileChecker.CheckImageFileName(zipItem.FileName) Then fileList.Add(comic.TempFolder & "/" & zipItem.FileName)
                            If FileOpener.CancellationPending Then e.Cancel = True : e.Result = String.Empty : Exit Sub
                            FileOpener.ReportProgress(6, x)
                        Next
                    End Using

                Case ArchiveType.PDF
                    If Not IO.Directory.Exists(comic.TempFolder) Then IO.Directory.CreateDirectory(comic.TempFolder)
                    Dim pdfDoc As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(comic.Path)
                    Dim counter As Integer = 1
                    For Each Page As PdfSharp.Pdf.PdfPage In pdfDoc.Pages
                        Dim resources As PdfSharp.Pdf.PdfDictionary = Page.Elements.GetDictionary("/Resources")
                        If Not resources Is Nothing Then
                            Dim xObjects As PdfSharp.Pdf.PdfDictionary = resources.Elements.GetDictionary("/XObject")
                            If Not xObjects Is Nothing Then
                                Dim items As ICollection(Of PdfSharp.Pdf.PdfItem) = xObjects.Elements.Values
                                For Each pdfItem As PdfSharp.Pdf.PdfItem In items
                                    Dim reference As PdfSharp.Pdf.Advanced.PdfReference = CType(pdfItem, PdfSharp.Pdf.Advanced.PdfReference)
                                    If Not reference Is Nothing Then
                                        Dim xObject As PdfSharp.Pdf.PdfDictionary = CType(reference.Value, PdfSharp.Pdf.PdfDictionary)
                                        ' Ensure the Object is an external Object and an image 
                                        If Not xObject Is Nothing AndAlso String.Compare(xObject.Elements.GetString("/Subtype"), "/Image") = 0 Then
                                            Dim filter As String = xObject.Elements.GetName("/Filter")
                                            Select Case filter
                                                Case "/DCTDecode"
                                                    counter += 1
                                                    Dim stream As Byte() = xObject.Stream.Value
                                                    Dim fName As String = comic.TempFolder & "/" & String.Format("page{0}.jpg", counter.ToString("0000"))
                                                    Dim fs As New System.IO.FileStream(fName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
                                                    Dim bw As New System.IO.BinaryWriter(fs)
                                                    bw.Write(stream)
                                                    bw.Flush()
                                                    bw.Close()
                                                    fs.Close()
                                                    fs.Dispose()
                                                    bw = Nothing
                                                    fs = Nothing
                                                    fileList.Add(fName)
                                                Case "/FlateDecode"
                                                Case Else
                                                    ' Do Nothing 
                                            End Select
                                        End If ' Not xObject Is Nothing 
                                    End If ' Not reference Is Nothing 
                                Next
                            End If
                        End If
                    Next ' Page In pdfDoc.Pages 
                    If counter = 0 OrElse fileList.Count = 0 Then
                        e.Cancel = True
                        e.Result = "Unable to process PDF file."
                        Exit Sub
                    End If

                Case ArchiveType.OpenDirectory
                    Dim x As Integer = IO.Directory.GetFiles(comic.Path).Count
                    FileOpener.ReportProgress(5, x)
                    For Each fn As String In IO.Directory.GetFiles(comic.Path)
                        If FileChecker.CheckImageFileName(fn) Then fileList.Add(fn)
                        If FileOpener.CancellationPending Then e.Cancel = True : e.Result = String.Empty : Exit Sub
                        FileOpener.ReportProgress(6, x)
                    Next
                Case Else
                    e.Cancel = True : Exit Sub
            End Select

            fileList.Sort()
            For Each s As String In fileList
                Dim x As New comicPage(s)
                FileOpener.ReportProgress(3, x)
                If FileOpener.CancellationPending Then e.Cancel = True : e.Result = String.Empty : Exit Sub
            Next ' Each String In fileList 

            e.Result = fileName
        Catch ex As Exception
            Debug.WriteLine(ex.ToString)
            FileOpener.ReportProgress(-1, ex)
            e.Cancel = True
            e.Result = ex
        End Try
    End Sub ' FileOpener_DoWork 

    Private Sub FileOpener_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles FileOpener.ProgressChanged
        Select Case e.ProgressPercentage
            Case 1 ' Set Reading List 
                Me._rl = e.UserState
                Me.prgLoading.Value = 0
            Case 2 ' Set Comic 
                Me.prgLoading.Value = 0
                If Not Me._comic Is Nothing Then Me._comic.Dispose()
                Me._comic = e.UserState
                OnPropertyChanged("Pages")
                'lstPages.ItemsSource = _comic.ComicPages
                'Me.lstPageNames.ItemsSource = _comic.ComicPages
                'Me.lstPagesBottom.ItemsSource = _comic.ComicPages
                '  lstPages.SelectedIndex = 0
            Case 5
                Me.prgLoading.Value = 0
                Me.prgLoading.Maximum = e.UserState
                Me.prgLoading.Value = 0
            Case 6
                Me.prgLoading.Value = Me.prgLoading.Value + 1
            Case -1
                Dim ex As Exception = e.UserState
                Debug.WriteLine(ex.ToString)
                MsgBox("There was an error opening the selected file.", MsgBoxStyle.Critical, "eComic - File Open Error")
            Case Else
                Me._comic.ComicPages.Add(CType(e.UserState, comicPage))
                OnPropertyChanged("Pages")
                '  lstPages.Items.Refresh()
                '  Me.lstPageNames.Items.Refresh()
                ' If Me._comic.ComicPages.Count = 1 Then lstPages.SelectedIndex = 0
                Me.prgLoading.Value = Me.prgLoading.Value + 1
        End Select ' Case e.ProgressPercentage 
    End Sub ' FileOpener_ProgressChanged 

    Private Sub FileOpener_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles FileOpener.RunWorkerCompleted
        Me.Cursor = Cursors.Arrow
        Me.prgLoading.Value = 0
        If e.Cancelled Then
            '    If Not e.Result.GetType Is GetType(Exception) Then
            If Not Me._comic Is Nothing Then Me._comic.Dispose() : Me._comic = Nothing
            If Not Me._rl Is Nothing Then Me._rl.Dispose() : Me._rl = Nothing

            If String.IsNullOrEmpty(e.Result) Then
                MsgBox("Open File Request Was Cancelled.", MsgBoxStyle.Information)
            Else
                MsgBox(e.Result, MsgBoxStyle.Information)
            End If
            Me.Cursor = Cursors.Arrow
            Exit Sub
            'End If
        End If ' e.Cancelled 
        Dim fn As String = e.Result
        My.Settings.LastFileOpened = fn
        If _comic.ArchiveType <> ArchiveType.OpenDirectory Then Me.MRU.Append(New MostRecentFile(fn, True, 0))
        Me.mruList.Items.Refresh()
        Me.lstPages.SelectedIndex = _resumeReadingVal
        _resumeReadingVal = 0
        Me.sldPageNmbers.Maximum = Me.PageCount
        Me.sldPageNmbers.Value = Me.lstPages.SelectedIndex
        Debug.WriteLine("Pages: " & _comic.ComicPages.Count)
        Me.DataContext = Me
        Debug.WriteLine("Pages In Lisbox: " & lstPages.Items.Count)
        Me.ElementRefreshes()
        Me.Cursor = Cursors.Arrow
    End Sub

#End Region

#Region "Save File Proces"
    Private Class sf_opt
        Public saveFileName As String
        Public comic As Comic
        Public zip As Ionic.Zip.ZipFile
    End Class

    Private Sub saveFileBGW_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles saveFileBGW.DoWork
        Dim zip1 As New Ionic.Zip.ZipFile

        Dim ust As sf_opt = e.Argument

        For Each p As comicPage In ust.comic.ComicPages
            zip1.AddFile(p.FullPath, IO.Path.GetFileNameWithoutExtension(ust.saveFileName))
            saveFileBGW.ReportProgress(1)
        Next

        ust.zip = zip1
        e.Result = ust
    End Sub

    Private Sub saveFileBGW_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles saveFileBGW.ProgressChanged
        Me.prgLoading.Value = Me.prgLoading.Value + e.ProgressPercentage
    End Sub

    Private Sub saveFileBGW_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles saveFileBGW.RunWorkerCompleted
        Dim ust As sf_opt = e.Result
        ust.zip.Save(ust.saveFileName)
        Me.Cursor = Cursors.Arrow
    End Sub
#End Region

#Region "Window Events/Methods"

#Region "Full Screen Issues"
    Private Shared Function WindowProc(ByVal hwnd As System.IntPtr, ByVal msg As Integer, ByVal wParam As System.IntPtr, ByVal lParam As System.IntPtr, ByRef handled As Boolean) As System.IntPtr
        Select Case msg
            Case &H24
                WmGetMinMaxInfo(hwnd, lParam)
                handled = True
                Exit Select
        End Select

        Return New IntPtr(0)
    End Function

    Private Shared Sub WmGetMinMaxInfo(ByVal hwnd As System.IntPtr, ByVal lParam As System.IntPtr)

        Dim mmi As MINMAXINFO = DirectCast(Marshal.PtrToStructure(lParam, GetType(MINMAXINFO)), MINMAXINFO)

        ' Adjust the maximized size and position to fit the work area of the correct monitor
        Dim MONITOR_DEFAULTTONEAREST As Integer = &H2
        Dim monitor As System.IntPtr = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST)

        If monitor <> System.IntPtr.Zero Then

            Dim monitorInfo As New MONITORINFO()
            GetMonitorInfo(monitor, monitorInfo)
            Dim rcWorkArea As Rect = monitorInfo.rcWork
            Dim rcMonitorArea As Rect = monitorInfo.rcMonitor
            mmi.ptMaxPosition.X = Math.Abs(rcWorkArea.Left - rcMonitorArea.Left)
            mmi.ptMaxPosition.Y = Math.Abs(rcWorkArea.Top - rcMonitorArea.Top)
            mmi.ptMaxSize.X = Math.Abs(rcWorkArea.Right - rcWorkArea.Left)
            mmi.ptMaxSize.Y = Math.Abs(rcWorkArea.Bottom - rcWorkArea.Top)
        End If

        Marshal.StructureToPtr(mmi, lParam, True)
    End Sub

    Public Structure MINMAXINFO
        Public ptReserved As Point
        Public ptMaxSize As Point
        Public ptMaxPosition As Point
        Public ptMinTrackSize As Point
        Public ptMaxTrackSize As Point
    End Structure

    Public Class MONITORINFO
        Public cbSize As Integer = Marshal.SizeOf(GetType(MONITORINFO))

        Public rcMonitor As New Rect()
        Public rcWork As New Rect()
        Public dwFlags As Integer = 0
    End Class

    Protected Sub win_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)

    End Sub
    Protected Sub win_sourceInitialized(ByVal sender As Object, ByVal e As EventArgs)
        Dim handle As System.IntPtr = (New WindowInteropHelper(Me)).Handle
        HwndSource.FromHwnd(handle).AddHook(New HwndSourceHook(AddressOf WindowProc))

    End Sub

    <DllImport("user32")> Friend Shared Function GetMonitorInfo(ByVal hMonitor As IntPtr, ByVal lpmi As MONITORINFO) As Boolean
    End Function
    <DllImport("User32")> Friend Shared Function MonitorFromWindow(ByVal handle As IntPtr, ByVal flags As Integer) As IntPtr
    End Function

#End Region

    Public Sub DetectScreenRotation(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim theScreenBounds As System.Drawing.Rectangle
        ' TODO :  Determine way to find the CURRENTLY used screen 
        theScreenBounds = Forms.Screen.GetBounds(Forms.Screen.PrimaryScreen.Bounds)
        If theScreenBounds.Height > theScreenBounds.Width Then
            Debug.WriteLine("Running in Portriate mode")
            goToPortriatMode()
        Else ' theScreenBounds.Height > theScreenBounds.Width 
            Debug.WriteLine("Running in Landscape mode")
            goToLandscapeMode()
        End If ' theScreenBounds.Height > theScreenBounds.Width 
    End Sub
#End Region

#Region "Menu Command Objects"
#Region "Go To Page"
    Private Sub GotoPage_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)
        If Not Me._comic Is Nothing AndAlso Me._comic.ComicPages.Count > 0 Then
            e.CanExecute = True
        Else ' Not Me._comic Is Nothing 
            e.CanExecute = False
        End If ' Not Me._comic Is Nothing 
    End Sub

    Private Sub GotoPage_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        runGoToPage()
    End Sub

#End Region

#Region "Opening File Commands"
    Private Sub ResumeReadingArchive_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        If FileOpener.IsBusy Then FileOpener.CancelAsync()
        While FileOpener.IsBusy
            ' Endless loop 
        End While
        _resumeReadingVal = My.Settings.LastFileStoppedPage
        If Not String.IsNullOrEmpty(My.Settings.LastFileOpened) AndAlso IO.File.Exists(My.Settings.LastFileOpened) Then
            FileOpener.RunWorkerAsync(My.Settings.LastFileOpened)
        End If
    End Sub
    Private Sub ResumeReadingArchive_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)
        If String.IsNullOrEmpty(My.Settings.LastFileOpened) OrElse Not IO.File.Exists(My.Settings.LastFileOpened) Then
            e.CanExecute = False
        Else ' String.IsNullOrEmpty(My.Settings.LastFileOpened) 
            e.CanExecute = True
        End If ' String.IsNullOrEmpty(My.Settings.LastFileOpened) 
    End Sub

    Private Sub OpenCommand_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        RunOpenCommand()
    End Sub

    Private Sub mruList_MostRecentFileSelected(ByVal sender As System.Object, ByVal e As Microsoft.Windows.Controls.Ribbon.MostRecentFileSelectedEventArgs)
        Dim fn As String = CType(e.SelectedItem, MostRecentFile).FilePath
        If Len(Trim(fn)) > 0 AndAlso IO.File.Exists(fn) Then
            If Me.FileOpener.IsBusy Then Me.FileOpener.CancelAsync()
            Me.Cursor = Cursors.Wait
            FileOpener.RunWorkerAsync(fn)
        Else ' Len(Trim(fn)) > 0 AndAlso IO.File.Exists(fn) 
            MsgBox("The selected file does not exist.", MsgBoxStyle.Information, "eComic")
        End If ' Len(Trim(fn)) > 0 AndAlso IO.File.Exists(fn) 
    End Sub

    Private Sub OpenDirCommand_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        RunOpenDirCommand()
    End Sub

    Private Sub PreviousArchive_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)
        If Not _comic Is Nothing AndAlso Not _rl Is Nothing AndAlso _rl.HasPrevious Then
            e.CanExecute = True
        Else
            e.CanExecute = False
        End If
    End Sub

    Private Sub PreviousArchive_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        goToOtherArchive(False)
    End Sub

    Private Sub NextArchive_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)
        If Not _comic Is Nothing AndAlso Not _rl Is Nothing AndAlso _rl.HasNext Then
            e.CanExecute = True
        Else
            e.CanExecute = False
        End If
    End Sub

    Private Sub NextArchive_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        goToOtherArchive(True)
    End Sub

#End Region

#Region "Save Command"
    Private Sub Savecommand_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)
        If Not _comic Is Nothing AndAlso ArchiveType.OpenDirectory = _comic.ArchiveType Then
            e.CanExecute = True
        Else
            e.CanExecute = False
        End If
    End Sub

    Private Sub Savecommand_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        Dim dx As New Windows.Forms.SaveFileDialog

        dx.CheckFileExists = False
        dx.AddExtension = True
        dx.CheckPathExists = False
        dx.CreatePrompt = False

        dx.DefaultExt = "cbz"
        dx.Filter = "Comic Book Archive (*.cbz) |*.cbz;*.zip"
        dx.FileName = _comic.FileName
        dx.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments

        Dim dlg As Windows.Forms.DialogResult = dx.ShowDialog
        If dlg = Forms.DialogResult.OK Then
            If FileOpener.IsBusy Then
                MsgBox("There is currently a file being opened.", MsgBoxStyle.Information, "eComic")
                Exit Sub
            End If
            If saveFileBGW.IsBusy Then
                MsgBox("This directory is currently in the process of being saved.", MsgBoxStyle.Information, "eComic")
                Exit Sub
            End If
            Me.Cursor = Cursors.Wait
            Me.prgLoading.Maximum = Me._comic.ComicPages.Count
            Me.prgLoading.Value = 0
            Dim xy1 As New sf_opt
            xy1.saveFileName = dx.FileName
            xy1.comic = _comic
            Me.saveFileBGW.RunWorkerAsync(xy1)
        End If ' dlg = Forms.DialogResult.OK 
    End Sub

#End Region

#Region "Other Commands"
    Private Sub OptionsCommand_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        Dim opt As New OptionsDialog
        opt.ShowDialog()
    End Sub

    Private Sub ExitApplicationCommand_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        ' TODO : Add Comic Clean-Up Functionality Here 
        Me.Close()
    End Sub

    Private Sub FullScreenCommand_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        Me.goFullScreen()
    End Sub
#End Region
#End Region

#Region "Image Tab Commands"

    Private Sub imgFull_MouseLeftButtonDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        Dim tt = DirectCast(DirectCast(imgFull.RenderTransform, TransformGroup).Children.First(Function(tr) TypeOf tr Is TranslateTransform), TranslateTransform)
        start = e.GetPosition(imgBorder)
        origin = New Point(tt.X, tt.Y)
        imgFull.CaptureMouse()
        Me.Cursor = Cursors.ScrollAll
    End Sub

    Private Sub imgFull_MouseWheel(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseWheelEventArgs)
        If CBool(My.Settings.MouseWheelZoom) Then
            Dim zoom As Double = IIf(e.Delta > 0, 0.2, -0.2)
            performZoom(zoom)
        Else ' CBool(My.Settings.MouseWheelZoom) 
            navigateList(Not (e.Delta > 0))
        End If ' CBool(My.Settings.MouseWheelZoom) 
        e.Handled = True
    End Sub

    Private Sub imgFull_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseEventArgs)
        If imgFull.IsMouseCaptured Then
            Dim tt = DirectCast(DirectCast(imgFull.RenderTransform, TransformGroup).Children.First(Function(tr) TypeOf tr Is TranslateTransform), TranslateTransform)
            Dim v As Vector = start - e.GetPosition(imgBorder)
            'tt.X = origin.X - v.X
            'tt.Y = origin.Y - v.Y
            tt.BeginAnimation(TranslateTransform.XProperty, CreatePanAnimation(origin.X - v.X), HandoffBehavior.Compose)
            tt.BeginAnimation(TranslateTransform.YProperty, CreatePanAnimation(origin.Y - v.Y), HandoffBehavior.Compose)


            If imgFull.Stretch = Stretch.None Then
                If Not Me.lstPages.SelectedItem Is Nothing AndAlso Me.lstPages.SelectedItem.GetType Is GetType(comicPage) Then
                    Dim c As comicPage = Me.lstPages.SelectedItem
                    Dim x As New BitmapImage(c.FileNameUri)
                    x.CacheOption = BitmapCacheOption.None
                    Me.imgFull.Source = x
                End If ' Not Me.lstPages.SelectedItem Is Nothing  
            End If

            Me.imgFull.InvalidateVisual()

        End If ' imgFull.IsMouseCaptured 
        e.Handled = True
    End Sub

    Private Sub imgFull_MouseLeftButtonUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        imgFull.ReleaseMouseCapture()
        Me.Cursor = Cursors.Arrow
    End Sub

    Private Sub ZoomIn_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        performZoom(0.2)
    End Sub

    Private Sub ZoomOps_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)
        If Not Me._comic Is Nothing AndAlso Not Me.lstPages Is Nothing AndAlso Not Me.lstPages.SelectedItem Is Nothing AndAlso Me.lstPages.SelectedItem.GetType Is GetType(comicPage) Then
            e.CanExecute = True
        Else : e.CanExecute = False
        End If ' Not Me.lstPages.SelectedItem Is Nothing  
    End Sub

    Private Sub ZoomOut_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        performZoom(-0.2)
    End Sub

    Private Sub ZoomFit_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        reverseZoom(Stretch.Uniform)
    End Sub

    Private Sub Zoom1to1_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        reverseZoom(Stretch.None)
    End Sub



    Private Sub imgFull_PreviewMouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseEventArgs)
        Dim b As VisualBrush = DirectCast(magnifierEllipse.Fill, VisualBrush)
        Dim pos As Point = e.MouseDevice.GetPosition(Me.imgBorder)
        Dim viewbox As Rect = b.Viewbox
        Dim xOffset As Double = viewbox.Width / 2.0
        Dim yOffset As Double = viewbox.Height / 2.0
        viewbox.X = pos.X '- xOffset
        viewbox.Y = pos.Y '- yOffset
        viewbox.Width = My.Settings.LoupeMagnification
        viewbox.Height = My.Settings.LoupeMagnification

        b.Viewbox = viewbox
        ' Canvas.SetLeft(magnifierCanvas, pos.X - magnifierEllipse.Width / 2)
        ' Canvas.SetTop(magnifierCanvas, pos.Y - magnifierEllipse.Height / 2)
        Canvas.SetLeft(magnifierCanvas, pos.X)
        Canvas.SetTop(magnifierCanvas, pos.Y)
    End Sub

    Private Sub LoupeCommand_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)
        If Not _comic Is Nothing AndAlso Not Me.lstPages.SelectedItem Is Nothing AndAlso Me.lstPages.SelectedItem.GetType Is GetType(comicPage) Then
            e.CanExecute = True
        Else
            e.CanExecute = False
        End If
    End Sub



    Private Sub imgFull_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        If e.ChangedButton = MouseButton.Middle Then navigateList(True)
    End Sub
#End Region

#Region "Control Commands"
    Private Sub lstPages_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        Me.lblPageName.Content = ""
        Me.lblPageNumber.Content = ""
        Me.imgFull.DataContext = Nothing
        If Not Me.lstPages.SelectedItem Is Nothing AndAlso Me.lstPages.SelectedItem.GetType Is GetType(comicPage) Then
            Dim c As comicPage = Me.lstPages.SelectedItem
            Dim x As BitmapImage

            x = New BitmapImage(c.FileNameUri)
            x.CacheOption = BitmapCacheOption.None
            Me.imgFull.Source = x
            Me.lblPageName.Content = Me.CurrentFileName
            Me.lblPageNumber.Content = Me.CurrentPage
            My.Settings.LastFileStoppedPage = Me.lstPages.SelectedIndex
            Me.ppPageNames.IsOpen = False
            Me.lstPageNames.ScrollIntoView(Me.lstPageNames.SelectedItem)
            Me.lstPages.ScrollIntoView(Me.lstPages.SelectedItem)
            Me.sldPageNmbers.Value = Me.lstPages.SelectedIndex
        End If ' Not Me.lstPages.SelectedItem Is Nothing  
    End Sub ' lstPages_SelectionChanged 

    Private Sub lblPageName_MouseRightButtonDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        ppPageNames.IsOpen = True
    End Sub ' lblPageName_MouseRightButtonDown 

    Private Sub lblPageNumber_MouseRightButtonDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        Me.pageSlider.Maximum = _comic.ComicPages.Count
        Me.pageSlider.Value = Me.lstPages.SelectedIndex
        Me.ppPageNumber.IsOpen = True
    End Sub ' lblPageNumber_MouseRightButtonDown 

    Private Sub btnClosePageNumberPop_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Me.ppPageNumber.IsOpen = False
    End Sub ' btnClosePageNumberPop_Click 

    Private Sub pageSlider_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double))
        If Me.ppPageNumber.IsOpen Then
            Me.lstPages.SelectedIndex = e.NewValue
            Me.lstPages.ScrollIntoView(Me.lstPages.SelectedItem)
        End If ' Me.ppPageNumber.IsOpen 
    End Sub ' pageSlider_ValueChanged 

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If Not String.IsNullOrEmpty(Me._currentVersionUrl) Then System.Diagnostics.Process.Start(Me._currentVersionUrl)
    End Sub ' btnUpdate_Click 

    ''' <summary>
    ''' Used to handle when a new version is being reported from the Analytics Software 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub monitor_versionAvailable(ByVal sender As Object, ByVal e As EQATEC.Analytics.Monitor.VersionAvailableEventArgs)
        _currentVersionUrl = e.DownloadUri
        Me.DisplayUpdate = True
    End Sub ' monitor_versionAvailable 
#End Region

#Region "Full Screen Tool Bar Commands"
    Private Sub btnZoomIn_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Me.performZoom(0.2)
    End Sub

    Private Sub btnZoomOut_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Me.performZoom(-0.2)
    End Sub

    Private Sub btnZoomFill_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        reverseZoom(Stretch.Uniform)
    End Sub

    Private Sub btn1to1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        reverseZoom(Stretch.None)
    End Sub

    Private Sub btnNextPage_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Me.navigateList(True)
    End Sub

    Private Sub btnPreviousPage_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Me.navigateList(False)
    End Sub

    Private Sub btnLeaveFullScreen_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        exitFullScreen()
    End Sub

    Private Sub sldPageNmbers_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double))
        Me.lstPages.SelectedIndex = e.NewValue
    End Sub
#End Region



    ' In Development Items 

    Private Sub FileControls_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)

    End Sub

    Private Sub FileControls_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)

    End Sub


    Private Sub brightCommand_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)
        e.CanExecute = True
    End Sub

    Private Sub brightCommand_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)
        Me.Brightness += 0.1
    End Sub


    Private Sub cmdFavoriteCommand_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs)

    End Sub

    Private Sub cmdFavoriteCommand_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)

    End Sub
End Class
